package com.fzrskj.cloud.free.user.service;

import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.core.enums.diy.DiyProductStatusEnum;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.JsonNameUtils;
import com.fzrskj.cloud.free.miniservice.utils.DiyProductSyncUtils;
import com.fzrskj.cloud.free.sys.bean.SysProductView;
import com.fzrskj.cloud.free.sys.bean.SysPromotion;
import com.fzrskj.cloud.free.sys.utils.SysProductUtils;
import com.fzrskj.cloud.free.sys.utils.SysPromotionUtils;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.bean.UserDiyBean;
import com.fzrskj.cloud.free.user.bean.UserDiyViewBean;
import com.fzrskj.cloud.free.user.bean.UserDiyViewForMiniServerBean;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import com.fzrskj.cloud.free.user.utils.UserDiyUtils;
import com.fzrskj.cloud.free.user.utils.diy.UserDiyUpgradeUtils;
import ms.core.consts.Consts;
import ms.core.consts.SysErr;
import ms.core.db.ConnectionContext;
import ms.core.object.CObject;
import ms.core.tool.ClassTool;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;
import org.apache.commons.collections.map.HashedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserDiyService extends CObject {
    /**
     * code generated by pallas frame work
     *
     * @param req
     * @param resp
     * @param p={}
     * @param sid
     * @return
     */
    public String newUserDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        //TODO put your code here
        Map<String, Object> values = new HashMap<String, Object>();

        UserDiyUtils utls = new UserDiyUtils();
        int ret = utls.newUserDiy(values);
        String err = utls.getErrCode();
        utls.dispose();
        return XmlCodeParser.formatResultTips(ret > 0, err);
    }

    /**
     * code generated by pallas frame work
     *
     * @param req
     * @param resp
     * @param p={"id":n} or p={"ids":"id1,id2,..."}
     * @param sid
     * @return
     */
    public String delUserDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        //TODO put your code here
        String ids;
        int id = JsonTool.getIntValue(p, "id", -1);
        if (id > 0) {
            ids = String.format("%d", id);
        } else {
            ids = JsonTool.getStrValue(p, "ids", null);
        }

        if (StrTool.isBlankStr(ids)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        int n = 0;
        UserDiyUtils utls = new UserDiyUtils();
        List<String> list = StrTool.spilitString(ids, ",");
        for (int i = 0; i < list.size(); i++) {
            id = StrTool.strToIntDef(list.get(i), -1);
            if (id < 1) {
                continue;
            }

            //TODO delete by more condition
            if (utls.delUserDiy(id) > 0) {
                n++;
            }
        }
        utls.dispose();

        String code;
        String msg = String.format("共删除记录 %d ！", n);
        if (n > 0) {
            code = SysErr.CODE_SUCCESS;
        } else {
            code = SysErr.CODE_FAILURE;
        }
        return XmlCodeParser.formatResultTips(n > 0, code, msg);
    }

    /**
     * code generated by pallas frame work
     *
     * @param req
     * @param resp
     * @param p={"id":n,...}
     * @param sid
     * @return
     */
    public String modUserDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {

        int id = JsonTool.getIntValue(p, "id", -1);
        String startTime = CJsonTool.getStrValue(p, "startTime", null);
        String endTime = CJsonTool.getStrValue(p, "endTime", null);
        int renewMonthPrice = CJsonTool.getIntValue(p, "renewMonthPrice", -1);
        int renewYearPrice = CJsonTool.getIntValue(p, "renewYearPrice", -1);

        if (CStrTool.isBlankStr(startTime) || CStrTool.isBlankStr(endTime)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        Map<String, Object> cdt = new HashMap<>();
        cdt.put("id", id);

        Map<String, Object> values = new HashMap<>();
        values.put("startTime", startTime);
        values.put("endTime", endTime);
        values.put("renewMonthPrice", renewMonthPrice > 0 ? renewMonthPrice : "");
        values.put("renewYearPrice", renewYearPrice > 0 ? renewYearPrice : "");

        UserDiyUtils utls = new UserDiyUtils();
        int ret = utls.modUserDiy(values, cdt);
        String err = utls.getErrCode();
        utls.dispose();
        return XmlCodeParser.formatResultTips(ret > 0, err);
    }

    /**
     * 账号转移
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String userDiyMoveAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
        int id = JsonTool.getIntValue(p, "id", -1);
        String userName = CJsonTool.getStrValue(p, "userName", "");
        if("".equals(userName)){
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS);
        }
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccount userAccount = accountUtils.isRegister(userName);
        if(userAccount == null){
            return XmlCodeParser.formatCustomTips(false,"该转移账号不存在，请重新输入新");
        }
        Map<String, Object> cdt = new HashMap<>();
        cdt.put("id", id);
        Map<String, Object> values = new HashMap<>();
        values.put("userId",userAccount.getUserId());

        UserDiyUtils utls = new UserDiyUtils();
        int ret = utls.modTrandferAccount(values, cdt);
        String err = utls.getErrCode();
        utls.dispose();
        return XmlCodeParser.formatResultTips(ret > 0, err);
    }

    /**
     * 获取续费可选日期.
     *
     * @param request
     * @param response
     * @param p
     * @param sid
     * @return
     */
    public String getDiyPriceRenewPromotionList(HttpServletRequest request, HttpServletResponse response, String p, String sid) {
        String productCode = JsonTool.getStrValue(p, "productCode", "");
        int id = JsonTool.getIntValue(p, "id", -1);

        if (StrTool.isBlankStr(productCode)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        SysPromotionUtils promotionUtils = new SysPromotionUtils();
        List<SysPromotion> promotionList = promotionUtils.getSysPromotionList(productCode, id, 2);

        if (null == promotionList || promotionList.size() < 1) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "获取续费日期设置失败");
        }
        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, JsonTool.listBeanToJson(promotionList));
    }

    /**
     * code generated by pallas frame work
     *
     * @param req
     * @param resp
     * @param p={"key":n,...,"page":m,"pagesize":n}
     * @param sid
     * @return
     */
    public String queryUserDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        //TODO put your code here,such as get parameter or valid user login state
        int page = JsonTool.getIntValue(p, "page", 0);
        if (page < 1) {
            page = 1;
        }
        int pagesize = JsonTool.getIntValue(p, "pagesize", 0);
        if (pagesize < 1) {
            pagesize = Consts.PAGE_SIZE;
        }

        //TODO to put your code here
        Map<String, Object> cdt = new HashMap<String, Object>();

        UserDiyUtils utls = new UserDiyUtils();
        int rows = utls.queryUserDiy(cdt);
        int pages = this.calculatePages(rows, pagesize);
        if (pages < page) {
            utls.dispose();
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND);
        }
        List<UserDiyBean> rets = utls.queryUserDiy(cdt, "id desc", page, pagesize);
        String err = utls.getErrCode();
        utls.dispose();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            return XmlCodeParser.formatResultTips(false, err);
        }

        //TODO to replace your table code here
        return XmlCodeParser.formatResultTitlePageData(err, "XXXX", page, pages, pagesize, rows, JsonTool.listBeanToJson(rets));
    }

    /**
     * code generated by pallas frame work
     *
     * @param req
     * @param resp
     * @param p={"id":n}
     * @param sid
     * @return
     */
    public String getUserDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        //TODO put your code here
        int id = JsonTool.getIntValue(p, "id", -1);
        if (id < 1) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        UserDiyUtils utls = new UserDiyUtils();
        UserDiyBean ret = utls.queryUserDiy(id);
        String err = utls.getErrCode();
        utls.dispose();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            return XmlCodeParser.formatResultTips(false, err);
        }

        //TODO to replace your code here
        return XmlCodeParser.formatResultTitleData(true, err, "XXXX", JsonTool.beanToJson(ret));
    }

    /**
     * 用户获取开通的自定义产品
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String queryUserDiyList(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        int uid = CloudContextUtils.getSession().getUID();

        int page = JsonTool.getIntValue(p, "page", 0);
        if (page < 1) {
            page = 1;
        }
        int pagesize = JsonTool.getIntValue(p, "pagesize", 0);
        if (pagesize < 1) {
            pagesize = Consts.PAGE_SIZE;
        }

        Map<String, Object> cdt = new HashMap<String, Object>();
        cdt.put("userId", uid);

        String subClass = JsonTool.getStrValue(p, "subClass", "");
        if (!StrTool.isBlankStr(subClass)) {
            cdt.put("subClass", subClass);
        }
        String keyword = JsonTool.getStrValue(p, "keyword", "");
        if (!StrTool.isBlankStr(keyword)) {
            cdt.put("keyword", keyword);
        }
        Integer endDateType = JsonTool.getIntValue(p, "endDateType", 0);
        if (endDateType > 0) {
            cdt.put("endDateType", endDateType);
        }

        UserDiyUtils utls = new UserDiyUtils();
        int rows = utls.userQuery(cdt);
        int pages = this.calculatePages(rows, pagesize);
        if (pages < page) {
            utls.dispose();
            return XmlCodeParser.formatResultTips(true, SysErr.SYS_DATA_NOT_FOUND);
        }
        List<UserDiyViewBean> rets = utls.userQuery(cdt, "id desc", page, pagesize);
        String err = utls.getErrCode();
        utls.dispose();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            return XmlCodeParser.formatResultTips(false, err);
        }

        //TODO to replace your table code here
        return XmlCodeParser.formatResultTitlePageData(err, "XXXX", page, pages, pagesize, rows, JsonTool.listBeanToJson(rets));
    }

    /**
     * 获取管理自定义品列表.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String queryDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        int page = JsonTool.getIntValue(p, "page", 0);
        if (page < 1) {
            page = 1;
        }
        int pagesize = JsonTool.getIntValue(p, "pagesize", 0);
        if (pagesize < 1) {
            pagesize = Consts.PAGE_SIZE;
        }

        Map<String, Object> cdt = new HashMap<String, Object>();
        String subClass = JsonTool.getStrValue(p, "subClass", "");
        if (!StrTool.isBlankStr(subClass)) {
            cdt.put("subClass", subClass);
        }
        String keyword = JsonTool.getStrValue(p, "keyword", "");
        if (!StrTool.isBlankStr(keyword)) {
            cdt.put("keyword", keyword);
        }
        Integer endDateType = JsonTool.getIntValue(p, "endDateType", 0);
        if (endDateType > 0) {
            cdt.put("endDateType", endDateType);
        }

        String bstartTime = JsonTool.getStrValue(p, "bstartTime", "");
        String bendDate = JsonTool.getStrValue(p, "bendDate", "");
        String estartTime = JsonTool.getStrValue(p, "estartTime", "");
        String eendDate = JsonTool.getStrValue(p, "eendDate", "");

        if (!StrTool.isBlankStr(bstartTime)) {
            cdt.put("startFrom", bstartTime);
        }
        if (!StrTool.isBlankStr(bendDate)) {
            cdt.put("startLimit", bendDate);
        }
        if (!StrTool.isBlankStr(estartTime)) {
            cdt.put("start", estartTime);
        }
        if (!StrTool.isBlankStr(eendDate)) {
            cdt.put("end", eendDate);
        }

        UserDiyUtils utls = new UserDiyUtils();
        int rows = utls.adminQuery(cdt);
        int pages = this.calculatePages(rows, pagesize);
        if (pages < page) {
            utls.dispose();
            return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, "[]");
        }
        List<UserDiyViewBean> rets = utls.adminQuery(cdt, "id desc", page, pagesize);
        String err = utls.getErrCode();
        utls.dispose();
        if (null == rets && !err.equals(SysErr.CODE_SUCCESS)) {
            return XmlCodeParser.formatResultTips(false, err);
        }

        //TODO to replace your table code here
        return XmlCodeParser.formatResultTitlePageData(SysErr.CODE_SUCCESS, "XXXX", page, pages, pagesize, rows, JsonTool.listBeanToJson(rets));
    }

    /**
     * 获取自定义产品信息.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String getDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        Integer id = JsonTool.getIntValue(p, "id", 0);
        if (id < 1) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        Map<String, Object> cdt = new HashedMap();
        cdt.put("id", id);
        UserDiyUtils utls = new UserDiyUtils();
        List<UserDiyViewBean> rets = utls.adminQuery(cdt, "id desc", 1, 1);
        if (rets.isEmpty()) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND);
        }

        return XmlCodeParser.formatResultTitleData(true, SysErr.CODE_SUCCESS, "XXXX", JsonTool.beanToJson(rets.get(0)));
    }

    /**
     * 用户查询业务详情.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String queryUserDiyDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        int uid = CloudContextUtils.getSession().getUID();

        Integer id = JsonTool.getIntValue(p, "id", 0);
        if (id < 1) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        Map<String, Object> cdt = new HashedMap();
        cdt.put("id", id);
        cdt.put("userId", uid);
        UserDiyUtils utls = new UserDiyUtils();
        List<UserDiyViewBean> rets = utls.userQuery(cdt, "id desc", 1, 1);
        if (rets.isEmpty()) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND);
        }

        return XmlCodeParser.formatResultTitleData(true, SysErr.CODE_SUCCESS, "XXXX", JsonTool.beanToJson(rets.get(0)));
    }

    /**
     * 配置.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String diyConfig(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        Integer id = JsonTool.getIntValue(p, "id", 0);
        String configInfo = JsonTool.getStrValue(p, "configInfo", "");
        if (id < 1) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
		/*if (!StrTool.isBlankStr(configInfo)) {
			configInfo = EncryptUtils.decodeSession(configInfo);
			configInfo = EncryptUtils.encodeSave(configInfo);
		}*/

        UserDiyUtils diyUtils = new UserDiyUtils();

        UserDiyBean diyBean = diyUtils.queryUserDiy(id);
        if (null == diyBean) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND);
        }

        Map<String, Object> cdt = new HashedMap();
        cdt.put("id", id);
        Map<String, Object> data = new HashedMap();
        data.put("instanceInfo", configInfo);
        if (DiyProductStatusEnum.WAIT.equals(diyBean.getStatus())) {
            data.put("status", DiyProductStatusEnum.NORMAL.getStatus());
        }


        diyUtils.modUserDiy(data, cdt);
        String err = diyUtils.getErrCode();
        diyUtils.dispose();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            return XmlCodeParser.formatResultTips(false, err);
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 暂停使用.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String pausedDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        String ids = JsonTool.getStrValue(p, "ids", "");
        if (StrTool.isBlankStr(ids)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        UserDiyUtils diyUtils = new UserDiyUtils();

        String[] idArr = ids.split(",");
        for (String idString : idArr) {
            Map<String, Object> cdt = new HashedMap();
            Integer id = Integer.valueOf(idString);
            cdt.put("id", id);
            Map<String, Object> data = new HashedMap();
            data.put("status", DiyProductStatusEnum.STOP.getStatus());

            diyUtils.modUserDiy(data, cdt);
            String err = diyUtils.getErrCode();
            diyUtils.dispose();
            if (!err.equals(SysErr.CODE_SUCCESS)) {
                return XmlCodeParser.formatResultTips(false, err);
            }
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 到期停用.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String diyExpireUsDisable(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        String ids = JsonTool.getStrValue(p, "ids", "");
        if (StrTool.isBlankStr(ids)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        UserDiyUtils diyUtils = new UserDiyUtils();

        String[] idArr = ids.split(",");
        for (String idString : idArr) {
            Map<String, Object> cdt = new HashedMap();
            Integer id = Integer.valueOf(idString);
            cdt.put("id", id);
            Map<String, Object> data = new HashedMap();
            data.put("status", DiyProductStatusEnum.EXPIRE.getStatus());

            diyUtils.modUserDiy(data, cdt);
            String err = diyUtils.getErrCode();
            diyUtils.dispose();
            if (!err.equals(SysErr.CODE_SUCCESS)) {
                return XmlCodeParser.formatResultTips(false, err);
            }
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 恢复使用
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String diyResume(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        String ids = JsonTool.getStrValue(p, "ids", "");
        if (StrTool.isBlankStr(ids)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        UserDiyUtils diyUtils = new UserDiyUtils();

        String[] idArr = ids.split(",");
        for (String idString : idArr) {
            Map<String, Object> cdt = new HashedMap();
            Integer id = Integer.valueOf(idString);
            cdt.put("id", id);
            Map<String, Object> data = new HashedMap();
            data.put("status", DiyProductStatusEnum.NORMAL.getStatus());

            diyUtils.modUserDiy(data, cdt);
            String err = diyUtils.getErrCode();
            diyUtils.dispose();
            if (!err.equals(SysErr.CODE_SUCCESS)) {
                return XmlCodeParser.formatResultTips(false, err);
            }
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 到期提醒.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String diyExpireUsRemind(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        String ids = JsonTool.getStrValue(p, "ids", "");
        if (StrTool.isBlankStr(ids)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        String alertWay = CJsonTool.getStrValue(p, "alertWay", "");
        if (StrTool.isBlankStr(alertWay)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR, "请至少选择一种通知方式");
        }

        UserDiyUtils diyUtils = new UserDiyUtils();

        String[] idArr = ids.split(",");
        Integer i = 0;
        for (String idString : idArr) {
            i++;
            Map<String, Object> cdt = new HashedMap();
            Integer id = Integer.valueOf(idString);
            UserDiyBean diyBean = diyUtils.queryUserDiy(id);


            //通知.
            Boolean result = diyUtils.sendAlert(id, alertWay);
            if (!result) {
                return XmlCodeParser.formatResultTips(false, diyUtils.getErrCode(), "处理第（" + i + "）个时发生错误：" + diyUtils.getErrCode());
            }
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 删除.
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String deleteDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        String ids = JsonTool.getStrValue(p, "ids", "");
        if (StrTool.isBlankStr(ids)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        UserDiyUtils diyUtils = new UserDiyUtils();

        String[] idArr = ids.split(",");
        for (String idString : idArr) {
            Map<String, Object> cdt = new HashedMap();
            Integer id = Integer.valueOf(idString);
            cdt.put("id", id);
            Map<String, Object> data = new HashedMap();
            data.put("isdel", 1);

            diyUtils.modUserDiy(data, cdt);
            String err = diyUtils.getErrCode();
            if (!err.equals(SysErr.CODE_SUCCESS)) {
                return XmlCodeParser.formatResultTips(false, err);
            }


            //通知第三方
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        UserDiyUtils diyUtil = new UserDiyUtils();
                        UserDiyBean diyBean = diyUtil.queryUserDiy(id);
                        SysProductUtils productUtils = new SysProductUtils();
                        SysProductView productView = productUtils.querySysProduct(ProductTypeEnum.DIY.getTag(), diyBean.getProductCode());
                        JSONObject productParam = JSONObject.parseObject(productView.getProductParam());
                        String paramShow = productParam.getString("paramShow");
                        if ("diy".equals(paramShow)) {
                            String miniServer = productParam.getString("miniServer");
                            JSONObject orderParam = JSONObject.parseObject(diyBean.getOpenInfo());

                            DiyProductSyncUtils syncUtils = new DiyProductSyncUtils();
                            syncUtils.syncDelete(miniServer, String.valueOf(diyBean.getId()));
                        }
                    } finally {
                        ConnectionContext.closeAllConnection();
                    }
                }
            }).start();

        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 管理自定义产品统计
     *
     * @param req
     * @param resp
     * @param p
     * @param sid
     * @return
     */
    public String queryNewDiyState(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        Map<String, Object> cdt = new HashedMap();

        UserDiyUtils diyUtils = new UserDiyUtils();
        //全部
        Integer countAll = diyUtils.adminQuery(cdt);
        //今天
        Date date = new Date();
        cdt.put("startFrom", CDateTimeTool.getDivDay(date, 0));
        cdt.put("startLimit", CDateTimeTool.getDivDay(date, 0));
        Integer countOpenInToday = diyUtils.adminQuery(cdt);
        //7天内开通
        cdt.put("startFrom", CDateTimeTool.getDivDay(date, -7));
        Integer countOpenInSevenDay = diyUtils.adminQuery(cdt);
        //7天到期
        cdt.remove("startLimit");
        cdt.remove("startFrom");
        cdt.put("endDateType", 7);
        Integer countExpireSevenDay = diyUtils.adminQuery(cdt);
        //已到期
        cdt.put("endDateType", 1);
        Integer countExpired = diyUtils.adminQuery(cdt);

        Map<String, Object> data = new HashedMap();
        data.put("all", countAll);
        data.put("openToday", countOpenInToday);
        data.put("openSevenDay", countOpenInSevenDay);
        data.put("expireSevenDay", countExpireSevenDay);
        data.put("countExpired", countExpired);

        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, JsonTool.beanToJson(data));
    }

    /**
     * 微服务接口：修改业务状态和配置信息.
     */
    public String diyProductPublicModify(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        Integer businessId = JsonTool.getIntValue(p, "business_id", 0);
        Integer status = JsonTool.getIntValue(p, "status", 0);
        String instanceInfo = JsonTool.getStrValue(p, "instance_info", "");

        //参数校验
        if (businessId < 1 || (status != 99 && status != 1 && status != 2 && status != 3)) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        //验证业务
        UserDiyUtils diyUtils = new UserDiyUtils();
        UserDiyBean diyBean = diyUtils.queryUserDiy(businessId);
        if (null == diyBean) {
            return XmlCodeParser.formatResultTips(false, "BUSINESS_NOT_FOUND", "业务不存在");
        }

        //更新数据
        Map<String, Object> update = new HashedMap();
        update.put("status", status);
        update.put("instanceInfo", instanceInfo);

        Map<String, Object> where = new HashedMap();
        where.put("id", businessId);
        Integer affect = diyUtils.modUserDiy(update, where);

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }

    /**
     * 微服务接口：获取业务信息.
     */
    public String diyProductPublicGet(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        Integer id = JsonTool.getIntValue(p, "business_id", 0);
        if (id < 1) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }
        Map<String, Object> cdt = new HashedMap();
        cdt.put("id", id);
        UserDiyUtils utls = new UserDiyUtils();
        List<UserDiyViewBean> rets = utls.userQuery(cdt, "id desc", 1, 1);
        if (rets.isEmpty()) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND);
        }

        UserDiyViewBean viewBean = rets.get(0);

        UserDiyViewForMiniServerBean miniServerBean = ClassTool.copy(viewBean, UserDiyViewForMiniServerBean.class);
        miniServerBean.setBusinessId(viewBean.getId());
        miniServerBean.setOpenInfo(JsonNameUtils.JsonEncode(JSONObject.parseObject(miniServerBean.getOpenInfo())));
        miniServerBean.setApplyTime(CDateTimeTool.formatDateTime(viewBean.getStartTime(), CDateTimeTool.TIME_FORMATE_FULL));
        miniServerBean.setEndTime(CDateTimeTool.formatDateTime(viewBean.getEndTime(), CDateTimeTool.TIME_FORMATE_FULL));

        String response = JsonNameUtils.JsonEncode(miniServerBean);

        return XmlCodeParser.formatResultTitleData(true, SysErr.CODE_SUCCESS, "XXXX", response);
    }

    /**
     * 添加升级到购物车.
     */
    public String addUserCartDiyUpgrade(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
        Integer id = JsonTool.getIntValue(p, "id", 0);
        String orderDescribe = JsonTool.getStrValue(p, "order_describe", "");
        net.sf.json.JSONObject diyParams = CJsonTool.getJSONObject(p, "diy_params", null);

        //参数校验.
        if (id < 1 || StrTool.isBlankStr(orderDescribe) || null == diyParams) {
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        //添加购物车.
        UserDiyUpgradeUtils upgradeUtils = new UserDiyUpgradeUtils();
        Boolean flag = upgradeUtils.addUpgradeUserCart(CloudContextUtils.getSession().getUID(), id, JSONObject.parseObject(p, Map.class));
        if (!flag) {
            return XmlCodeParser.formatResultTips(false, upgradeUtils.getErrCode(), upgradeUtils.getMsg());
        }

        return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
    }
}